#pragma once

#include <iostream>
#include <vector>
#include <string>
#include <queue>
#include <pthread.h>

struct ThreadInfo
{
    std::string _name;
    pthread_t _tid;
};

const int defaultnum = 5;
template <class T>
class ThreadPool
{
private:
    void Lock()
    {
        pthread_mutex_lock(&_mtx);
    }
    void Unlock()
    {
        pthread_mutex_unlock(&_mtx);
    }

    void WakeUp()
    {
        pthread_cond_signal(&_cond);
    }

    void ThreadSleep()
    {
        pthread_cond_wait(&_cond, &_mtx);
    }

    bool IsQueueEmpty()
    {
        return _tasks.empty();
    }

    std::string GetPthreadName(pthread_t tid)
    {
        for (int i = 0; i < _threads.size(); ++i)
        {
            if (_threads[i]._tid == tid)
            {
                return _threads[i]._name;
            }
        }
        return nullptr;
    }

public:
    static void *HandleTask(void *argv)
    {
        ThreadPool<T> *tp = (ThreadPool<T> *)argv;
        while (true)
        {
            // 拿到
            tp->Lock();
            while (tp->IsQueueEmpty())
            {
                tp->ThreadSleep();
            }
            T t = tp->Pop();
            
            tp->Unlock();

            // 处理
            t();
        }
    }

    T Pop()
    {
        T t = _tasks.front();
        _tasks.pop();
        return t;
    }

    void start()
    {
        std::cout << "start beign..." << std::endl;

        int num = _threads.size();
        for (int i = 0; i < num; ++i)
        {
            _threads[i]._name = "Thread-" + std::to_string(i + 1);
            pthread_create(&(_threads[i]._tid), nullptr, HandleTask, this);
        }
    }

    void Push(const T &task)
    {
        Lock();
        _tasks.push(task);
        WakeUp();

        Unlock();
    }

    static ThreadPool<T> *GetInstence(int n = defaultnum)
    {
        if (_tp == nullptr)
        {
            pthread_mutex_lock(&_lock);
            if (nullptr == _tp)
            {
                _tp = new ThreadPool<T>(n);
            }
            pthread_mutex_unlock(&_lock);
        }

        return _tp;
    }

private:
    ThreadPool(int n = defaultnum)
        : _threads(n)
    {
        pthread_mutex_init(&_mtx, nullptr);
        pthread_cond_init(&_cond, nullptr);
    }

    ~ThreadPool()
    {
        pthread_mutex_destroy(&_mtx);
        pthread_cond_destroy(&_cond);
    }

    ThreadPool(const ThreadPool<T>& tp) = delete;
    ThreadPool& operator=(const ThreadPool<T>& tp) = delete;
private:
    std::vector<ThreadInfo> _threads;
    std::queue<T> _tasks;

    pthread_mutex_t _mtx;
    pthread_cond_t _cond;

    static ThreadPool<T> *_tp;
    static pthread_mutex_t _lock;
};

template <class T>
ThreadPool<T> *ThreadPool<T>::_tp = nullptr;

template <class T>
pthread_mutex_t ThreadPool<T>::_lock = PTHREAD_MUTEX_INITIALIZER;
